using Zhaoxi.Zhihu.Core.Common;
using Zhaoxi.Zhihu.SharedKerel.Result;

namespace Zhaoxi.Zhihu.Core.QuestionAggregate.Entites;

public class Answer:AuditWithUserEntity
{
   
    public string Content { get; set; } = null!;
    
    public int QuestionId { get; set; }
    public Question Question { get; set; } = null!;
    
    public int LikeCount { get; private set; }
    
    public int DislikeCount { get; private set; }
    
    private readonly List<AnswerLike> _answerLikes = new();
    public IReadOnlyCollection<AnswerLike> AnswerLikes => _answerLikes.AsReadOnly();

    public Result AddLike(int userId, bool isLike)
    {
        var answerLike = _answerLikes.FirstOrDefault(like => like.UserId == userId);
        if (answerLike !=null) return Result. Failure("已赞或已踩");
        answerLike = new AnswerLike
        {
            UserId = userId,
            IsLike = isLike
        };
        _answerLikes.Add(answerLike);
        if (isLike) LikeCount += 1;
        else DislikeCount += 1;
        return Result. Success();
     }

  

    public void RemoveLike(int userId)
    {
        var answerLike = _answerLikes.FirstOrDefault(like => like.UserId == userId);
        if (answerLike == null) return;
        _answerLikes.Remove(answerLike);
        if (answerLike.IsLike) LikeCount -= 1;
        else DislikeCount -= 1;
    }

    public Result UpdateLike(int userId, bool isLike)
    {
        var answerLike = _answerLikes.FirstOrDefault(like => like.UserId == userId);

        if (answerLike == null) return Result.NotFound("未找到点赞记录");
        if (answerLike. IsLike == isLike) return Result. Failure("已赞或已踩");
        answerLike.IsLike = isLike;
        if (isLike)
        {
            LikeCount += 1;
            DislikeCount -= 1;
        }
        else
        {
            DislikeCount += 1;
            LikeCount -= 1;
        }

        return Result.Success();
    }
}